package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    //查询所有
    @Override
    public List<Category> findAll() {
      return categoryMapper.findall();
    }
    //保存
    @Override
    public void save(Category category) {

        category.setId(IdUtil.getSnowflake(1,1).nextId());
        //设置时间
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        //操作人设置
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
        //调用mapper
        categoryMapper.save(category);

    }

    @Override
    public void update(Category category) {
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        //执行修改
        categoryMapper.update(category);
    }
//删除分类
    //分类中菜品无法删除
    //分类有套菜无法删除
    //todo
    @Override
    public ResultInfo delect(long id) {
        //升级版 使用全局异常处理
        if ((categoryMapper.countdish(id)>0)){
            throw new CustomException("内部还有菜品，不可删除");
        }else if (categoryMapper.countmeal(id)>0){
            throw new CustomException("内部还有套餐，不可删除");
        }else {
            categoryMapper.delete(id);
            return ResultInfo.success(null);
        }


//        //判断分类下菜品室友为空
//        if (categoryMapper.countdish(id)>0){
//            return ResultInfo.error("内部有菜品，无法删除");
//        }else if (categoryMapper.countmeal(id)>0){
//            return ResultInfo.error("内部有套餐，无法删除");
//        }else {
//             categoryMapper.delete(id);
//             return ResultInfo.success(null);
//        }
    }

    @Override
    public List<Category> findtype(Integer type) {
        LambdaQueryWrapper<Category>categoryLambdaQueryWrapper=new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getType,type);
        return categoryMapper.selectList(categoryLambdaQueryWrapper);
    }


}